package com.example.springbootbaiduaidemo.utils;

import com.baidu.aip.imageclassify.AipImageClassify;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * @author chaird
 * @create 2020-10-29 19:36
 * https://console.bce.baidu.com/ai/#/ai/imagerecognition/overview/index
 */
@Component
public class BaiduAiUtils {

  @Autowired private AipImageClassify aipImageClassify;

  public Object animalDetect(String path) {
    // 传入可选参数调用接口
    HashMap<String, String> options = new HashMap<String, String>(2);
    options.put("top_num", "3");
    options.put("baike_num", "5");

    JSONObject res = aipImageClassify.animalDetect(path, options);
    //System.out.println(res.toString(2));
    return res;
  }
  public Object animalDetectOss(String ossUrl) {
    // 传入可选参数调用接口
    HashMap<String, String> options = new HashMap<String, String>(2);
    options.put("top_num", "3");
    options.put("baike_num", "5");
    byte[] fileStream = getFileStream(ossUrl);
    JSONObject res = aipImageClassify.animalDetect(fileStream, options);

    return res;
  }


  public static byte[] getFileStream(String url){
    try {
      URL httpUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
      conn.setRequestMethod("GET");
      conn.setConnectTimeout(5 * 1000);
      InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
      byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
      return btImg;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public static byte[] readInputStream(InputStream inStream) throws Exception{
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;
    while( (len=inStream.read(buffer)) != -1 ){
      outStream.write(buffer, 0, len);
    }
    inStream.close();
    return outStream.toByteArray();
  }

}
